package com.youthfilmic.yuejian.weixin.core;

import com.youthfilmic.yuejian.conn.WeixinConn;
import com.youthfilmic.yuejian.util.HttpUtil;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * Created by youweixi on 15/10/8.
 * 微信API方法
 */
public class WeixinAPI {

    /**
     * 获取access_token
     *
     * @return
     */
    public static String getToken() {
        String accessToken = null;
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WeixinConn.APP_ID+"&secret=" + WeixinConn.APP_SECRET;
        JSONObject jsonObject = HttpUtil.getJsonFromHttps(requestUrl, "GET", null);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                accessToken = jsonObject.getString("access_token");
                jsonObject.getInt("expires_in");
            } catch (JSONException e) {
                accessToken = null;
                // 获取token失败
                System.out.println("获取token失败 errcode:{} errmsg:{}"+jsonObject.getInt("errcode")+jsonObject.getString("errmsg"));
            }
        }
        return accessToken;
    }

    /**
     * @instruction 获取用户是否订阅的信息，如果订阅就刷新用户的资料，如果没有就返回false
     * 基于的接口和获取用户信息不同
     * @author Dxywx
     * @Time 2015.4.24
     * @ref http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html
     * */
    public static boolean getUserSubscribe(String openId){
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+TokenSystem.getTokenValue()+"&openid="+openId;
        System.out.println(requestUrl);
        JSONObject jsonObject = HttpUtil.getJsonFromHttps(requestUrl, "GET", null);
        if (jsonObject.containsKey("errcode")&&(jsonObject.getString("errcode")).equals("40001")){
            //TokenSystem.refreshTokenAndTicket();
            jsonObject = HttpUtil.getJsonFromHttps(requestUrl, "GET", null);
        }
        // 如果请求成功
        if (null != jsonObject) {
            try {
                //用户是否订阅，如果订阅返回1，否则返回0
                String subscribe = jsonObject.getString("subscribe");
                return !(subscribe == null || subscribe.trim().equals("0"));
            } catch (JSONException e) {
                // 获取token失败
                System.out.println("获取用户关注情况失败 errcode:{} errmsg:{}"+jsonObject.getInt("errcode")+jsonObject.getString("errmsg"));
            }
        }
        return true;
    }

    /**
     * @title 获取ticket
     * @author bigtomato
     * @time 2015.5.22
     *
     * */
    public static String getTicket(){
        //jsapiTicketUrl
        //获取JsapiTicket
        //用第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket（有效期7200秒，开发者必须在自己的服务全局缓存jsapi_ticket）：
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+TokenSystem.getTokenValue()+"&type=jsapi";
        JSONObject jsonObject = HttpUtil.getJsonFromHttps(requestUrl, "GET", null);
        String ticket = null;
        // 如果请求成功
        if (null != jsonObject) {
            try {
                int code = jsonObject.getInt("errcode");
                if (code == 0){
                    //"ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
                    //"expires_in":7200
                    ticket = jsonObject.getString("ticket");
                }
            } catch (JSONException e) {
                System.out.println("获取ticket失败 errcode:{} errmsg:{}"+jsonObject.getInt("errcode")+jsonObject.getString("errmsg"));
                ticket =  null;
            }
        }
        return ticket;
    }

}
